<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="axios.js"></script>
    <script>
      const request = axios.create({
        baseURL: 'http://localhost:8080', //主机地址
        timeout: 500, //超时时间 ms
        headers: {
          token: 'chan123',
        },
      })

      //请求拦截器
      request.interceptors.request.use(
        //请求成功
        (request) => {
          console.log('请求拦截')
          console.log('request', request)
          request.headers.mytoken = 'zany123'
          return request //放行
        },
        //请求失败
        (error) => {
          return Promise.reject(error)
        }
      )
      // 响应拦截器
      request.interceptors.response.use(
        // 响应成功
        function (response) {
          console.log('响应拦截')
          console.log('response', response)
          response.headers.mytoken = 'cqupt'
          return response //放行
        },
        // 响应失败
        function (error) {
          return Promise.reject(error)
        }
      )

      //基于promise
      request({
        method: 'get',
        url: '/user/list',
      })
        .then((response) => {
          console.log('获取数据成功', response)
        })
        .catch((error) => {
          console.log('获取数据失败', error)
        })

      //另一种写法
      request
        .get('/user/list')
        .then((response) => {
          console.log('获取数据成功1', response)
        })
        .catch((error) => {
          console.log('获取数据失败1', error)
        })
    </script>
  </body>
</html>
